<template>
<div class="infinite-container">
  <div class="tips-disabled center" v-if="outTime">
    您的订单已经失效！请重新预约
  </div>
  <div class="tips-warning center" v-else>
    支付剩余时间 {{m}}:{{s}}，超时自动失效
  </div>
  <mu-divider></mu-divider>
  <div v-if="!hasQRcode">
    <common-list title="挂号费用">
      <div class="confirm-money">
        ￥ {{doctor.charge}}
      </div>
    </common-list>
    <common-list title="支付方式" desc="微信支付"></common-list>
    <div class="login pd20">
      <mu-raised-button label="重新预约" @click="appoint" fullWidth primary class="btn-login" v-if="outTime"></mu-raised-button>
      <mu-raised-button label="立即支付" @click="pay" fullWidth primary class="btn-login" v-else></mu-raised-button>
    </div>
  </div>
  <div class="qrcode-wrapper center" v-else>
    <img :src="qrcodeSrc" width="200" />
    <div class="center mt20">
      长按此二维码<br/>选择 <i class="t1">识别图中二维码</i> 并支付
    </div>
  </div>
</div>
</template>

<script>
import {leftTime} from '../../common/js/util'
import CommonList from '../../components/CommonList'
import {commonAjax, ORG_ID, PLATFORM_PREFIX, SUBMIT_SOURCE} from '../../api/api'

export default {
  data () {
    return {
      m: 0,
      s: 0,
      outTime: false,
      doctor: JSON.parse(localStorage.doctor),
      order: JSON.parse(localStorage.order),
      hasQRcode: false,
      qrcodeSrc: ''
    }
  },
  mounted () {
    this.$store.commit('UPDATE_TITLE', '在线支付')
    // 订单默认失效时间
    const ORDER_OUT_DATE_TIME = 0
    let _this = this
    // fix ios getTime bug .replace(/-/g, "/")
    let serviceName = ''
    if (PLATFORM_PREFIX === 'cas') {
      serviceName = 'appService'
    } else {
      serviceName = 'wechatService'
    }
    commonAjax([], `${PLATFORM_PREFIX}.${serviceName}`, 'getServerTime').then(res => {
      if (res.data.code === 200) {
        let orderCreateTime = new Date(this.order.regCloseTimeDisplay.replace(/-/g, '/'))
        let dist = new Date(res.data.body.serverTime.replace(/-/g, '/')) - new Date()
        console.log(`regCloseTimeDisplay:${orderCreateTime}`)
        let timer = setInterval(() => {
          var left = leftTime(ORDER_OUT_DATE_TIME, (dist + (new Date() - orderCreateTime)))
          if (left.m <= 0 && left.s <= 0) {
            clearInterval(timer)
            _this.outTime = true
          } else {
            _this.m = left.m
            _this.s = left.s
          }
        }, 1000)
      }
    })
    // 预结算费用
    commonAjax([this.order.regRecordId, ORG_ID, 1], `${PLATFORM_PREFIX}.registrationService`, 'preBudget').then(res => {
      if (res.data.code === 200) {
        this.doctor.charge = res.data.body.selfAmount
      }
    })
  },
  methods: {
    pay () {
      let config = {
        orgId: ORG_ID,
        totalAmount: this.doctor.charge,
        accountType: '03',
        body: JSON.stringify({bustype: '11', id: this.order.regRecordId, source: SUBMIT_SOURCE}),
        outTradeNo: this.order.regSourceId,
        closePayTime: this.order.regClosePayTime,
        payModel: '2'
      }
      commonAjax([
        config
      ], `${PLATFORM_PREFIX}.payService`, 'getOrderStr').then(res => {
        console.log(res)
        if (res.data.code === 200) {
          this.qrcodeSrc = 'http://qr.liantu.com/api.php?text=' + res.data.body
          this.hasQRcode = true
          this.queryAliOrder()
        }
      }).catch(res => {
        console.warn(res)
      })
      // this.$router.push('/appointment/confirm-appoint-success')
    },
    appoint () {
      this.$router.push('/appointment/select-department')
    },
    queryAliOrder () {
      let i = 0
      const TIME_OUT = 60
      const PER_TIME = 3
      let _this = this
      this.timer = setInterval(() => {
        i++
        commonAjax([{
          orgId: ORG_ID,
          outTradeNo: this.order.regSourceId,
          accountType: '03'
        }], `${PLATFORM_PREFIX}.payService`, 'queryAliOrder').then(res => {
          if (res.data.body) {
            this.$router.push('/appointment/appoint-pay-success')
          } else if (i < (TIME_OUT / PER_TIME)) {
            console.log('checking order status...' + i)
          } else {
            clearInterval(_this.timer)
            this.$router.push('/appointment/history')
          }
        })
      }, PER_TIME * 1000)
    }
  },
  beforeDestroy () {
    this.$store.commit('UPDATE_TITLE')
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  components: {
    CommonList
  }
}
</script>

<style>
.paying {
  font-size:1.4em;
  text-align: center;
  padding-top: 4em;
  color: #999;
}
.qrcode-wrapper {
  width: 70%;
  height: 100px;
  margin: 2em auto;
}
</style>
